import $mConfig from '@/config/index.config.js'

let websocket = null
let socketConnectionFlag = false
let wsInterval = 0
let pingInterval = 0
let logoutFlag = false

let defaultData = null


function getWebsocket() {
	if (websocket) {
		return websocket
	} else {
		return initWs()
	}
}

function initWs() {
	clearTime()
	websocket = uni.connectSocket({
		url: $mConfig.wsUrl,
		success(data) {
			console.log('连接成功', data)
		},
		fail(err) {
			console.log('连接失败', err)
		}
	});
	websocket.onOpen(res => {
		socketConnectionFlag = true
		console.log('uni app websocket 连接成功', res)
		if(defaultData){
			sendMsg(defaultData)
		}
		sendHeart()
	})
	websocket.onClose(function(err) {
		console.log('uni app websocket 关闭', err)
		websocket = null
	})
	websocket.onError(function(err) {
		console.log("websocket error", err)
	})
	
	/**
	 * 收到消息
	 */
	websocket.onMessage(function(res){
		console.log('收到消息')
	})
	reconnection()
	return websocket
}




function sendMsg(data) {
	websocket.send({
		data: data,
		success() {
			console.log('发送成功')
		}
	})
}

function sendHeart() {
	pingInterval = setInterval(() => {
		websocket = getWebsocket()
		websocket.send({
			data: "0X9",
			success() {
				console.log("心跳发送成功")
			},
			fail() {
				console.log('心跳发送失败')
				socketConnectionFlag = false
				websocket.close()
				websocket = null
			}
		})
	}, 3000)
}

function reconnection() {
	wsInterval = setInterval(() => {
		if (!socketConnectionFlag&&!logoutFlag) {
			websocket = getWebsocket()
		}
	}, 1000)

}
function clearTime(){
	clearInterval(pingInterval)
	clearInterval(wsInterval)
}
function setLogoutFlag(flag){
	logoutFlag = flag
}

function setDefaultData(data){
	console.log('发送 login')
	this.defaultData = data
	sendMsg(data)
}
function close(){
	websocket.close()
}
export default {
	reconnection,
	sendMsg,
	getWebsocket,
	setLogoutFlag,setDefaultData,close
}
